import Vue from 'vue'
import Vuex from 'vuex'
import $H from '@/common/request.js';
Vue.use(Vuex)

export default new Vuex.Store({
	state:{
		user:'',
		token:'',
		
	},
	actions:{
		// 清除传输列表
		clearList({state}){
			uni.removeStorageSync('downList_'+state.user.id)
			uni.removeStorageSync('uploadList_'+state.user.id)
			state.downList=[]
			state.uploadList=[]
		},
		// 初始化下载任务
		initList({state}){
			if(state.user){
				let d=uni.getStorageSync('downList_'+state.user.id)
				let u=uni.getStorageSync('uploadList_'+state.user.id)
				state.downList=d?d:[]
				state.uploadList=u?u:[]
			}
		},
		// 创建下载任务
		createDownloadJob({state},obj){
			state.downList.unshift(obj)
			uni.setStorageSync('downList_'+state.user.id,state.downList)
		},
		// 更新下载任务进度
		updateDownloadJob({state},obj){
			let i=state.downList.findIndex(item=>item.key===obj.key)
			if(i!==-1){
				state.downList[i].progress=obj.progress
				state.downList[i].status=obj.status
				uni.setStorageSync('downList_'+state.user.id,state.downList)
			}
		},
		// 创建上传任务
		createUploadJob({state},obj){
			state.uploadList.unshift(obj)
			uni.setStorageSync('uploadList_'+state.user.id,state.uploadList)
		},
		// 更新上传任务进度
		updateUploadJob({state},obj){
			let i=state.uploadList.findIndex(item=>item.key===obj.key)
			console.log('out',obj.progress)
			if(i!==-1){
				console.log('in',obj.progress)
				state.uploadList[i].progress=obj.progress
				state.uploadList[i].status=obj.status
				uni.setStorageSync('uploadList_'+state.user.id,state.uploadList)
			}
		},
		
		// 初始化登录
		login({state},user){
			state.user=user
			state.token=user.token
			uni.setStorageSync('user',JSON.stringify(user))
			uni.setStorageSync('token',user.token)
		},
		// 初始化用户信息
		initUser({state}){
			let user=uni.getStorageSync('user')
			if(user){
				user=JSON.parse(user)
				state.user=user
				state.token=user.token
			}
		},
		// 退出登录
		logout(state){
			$H.post('/logout',{},{token:true})
			uni.removeStorageSync('user')
			uni.removeStorageSync('token')
			state.user=''
			state.token=''
			uni.reLaunch({
				url:'/pages/login/login'
			})
		}
		
	}
})